package com.vq3.digitalizationsoftwareintegrates.Servlet.MessageCenter;



import com.vq3.digitalizationsoftwareintegrates.Entity.Enum.MessageType;
import com.vq3.digitalizationsoftwareintegrates.Entity.Info.ResultInfo;
import com.vq3.digitalizationsoftwareintegrates.Entity.MessageCenter.*;
import com.vq3.digitalizationsoftwareintegrates.Entity.Spot_Check.MongoDBEntity.MongoDB_S_C_SaveSCDailyContextEntity;
import com.vq3.digitalizationsoftwareintegrates.Entity.Spot_Check.MongoDBEntity.MongoDB_S_C_SysAuthAuditMessageEntity;
import com.vq3.digitalizationsoftwareintegrates.Entity.Spot_Check.MongoDBEntity.MongoDB_S_C_WebSocketMessageEntity;
import com.vq3.digitalizationsoftwareintegrates.Entity.Spot_Check.MongoDBEntity.MongoDB_S_C_WebSocketSendMessageEntity;
import com.vq3.digitalizationsoftwareintegrates.Entity.Spot_Check.S_C_PointEntity;
import com.vq3.digitalizationsoftwareintegrates.Entity.User.*;
import com.vq3.digitalizationsoftwareintegrates.Service.MessageCenter.MessageCenterService;
import com.vq3.digitalizationsoftwareintegrates.Service.Spot_Check.Impl.Spot_Check_FusionServiceImpl;
import com.vq3.digitalizationsoftwareintegrates.Service.Spot_Check.Spot_Check_FusionService;
import com.vq3.digitalizationsoftwareintegrates.Service.User.UserFusionService;
import com.vq3.digitalizationsoftwareintegrates.Service.User.UserLoginService;
import com.vq3.digitalizationsoftwareintegrates.Servlet.WebSocket.WebSocketServer;
import com.vq3.digitalizationsoftwareintegrates.Utils.ImageUtil.CalculationIsType;
import com.vq3.digitalizationsoftwareintegrates.Utils.PackagedDataUtil.Impl.PackagedDataImpl;
import com.vq3.digitalizationsoftwareintegrates.Utils.PackagedDataUtil.PackagedData;
import com.vq3.digitalizationsoftwareintegrates.Utils.PermissionControl.GetUserPermission;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.EncodeException;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("messageCenter")
public class MessageCenterServlet {
    @Resource
    MessageCenterService messageCenterService;
    @Resource
    WebSocketServer webSocketServer;
    @Resource
    UserLoginService userLoginService;
    @Resource
    UserFusionService userFusionService;
    @Resource
    Spot_Check_FusionService spot_check_fusionService;
    @Resource
    Spot_Check_FusionService spot_check_fusionService1;
    @Resource
    GetUserPermission getUserPermission;



    @RequestMapping("messageCenterSidebar")
    public void findMessageCenterSidebarContext(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        PackagedData packagedData = new PackagedDataImpl();
        ResultInfo resultInfo = new ResultInfo();
        UserEntity userEntity = (UserEntity)httpServletRequest.getSession().getAttribute("USER");
        List<Permission_TBEntity> permission_tbEntities = getUserPermission.GetPermission(userEntity.getUname());
        Set<Integer> midS = new HashSet<>();
        resultInfo.setFlag(false);
        if (!permission_tbEntities.isEmpty()){
            for (Permission_TBEntity permission_tbEntity : permission_tbEntities) {
                List<MessageCenter_PerEntity> messageCenterEntities = messageCenterService.uidFindRoleIdFindMid(permission_tbEntity);
                if (!messageCenterEntities.isEmpty()){
                    for (MessageCenter_PerEntity messageCenterEntity : messageCenterEntities) {
                        midS.add(messageCenterEntity.getMid());
                    }
                }
            }
        }
        List<MessageCenterEntity> messageCenterEntities = messageCenterService.midFindMessageCenterSidBar(midS);
        if (!messageCenterEntities.isEmpty()){
            resultInfo.setFlag(true);
            resultInfo.setData(messageCenterEntities);
        }
        packagedData.writeValue(resultInfo,httpServletResponse);
    }
    @RequestMapping("messageSideBarCount")
    public void findMessageCount(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws EncodeException, IOException {
        PackagedData packagedData = new PackagedDataImpl();
        UserEntity userEntity = (UserEntity)httpServletRequest.getSession().getAttribute("USER");
        MongoDB_S_C_WebSocketSendMessageEntity mongoDB_s_c_webSocketSendMessageEntity = webSocketServer.onOpenFind_S_C_MessageToUser(userEntity.getUname());
        packagedData.writeValue(mongoDB_s_c_webSocketSendMessageEntity,httpServletResponse);
    }


    @RequestMapping("messageContext_S_C_Audit")
    public void  findMessageContext(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException {

        PackagedData packagedData = new PackagedDataImpl();
        ResultInfo resultInfo = new ResultInfo();
        List<MongoDB_S_C_WebSocketMessageEntity> mongoDB_s_c_webSocketMessageEntities = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        resultInfo.setFlag(false);
        for (GrantedAuthority authority : authorities) {
            if (authority.toString().equalsIgnoreCase("s3")) {
                Permission_TBEntity permission_tbEntity = new Permission_TBEntity(4, "s3", "点检系统的审核");
                mongoDB_s_c_webSocketMessageEntities = messageCenterService.rolesFindMongoDBToMongoDB_S_C_WebSocketMessageEntityS(permission_tbEntity);
            }
        }
        if (mongoDB_s_c_webSocketMessageEntities == null){
            resultInfo.setFlag(false);
        }else {
            resultInfo.setFlag(true);
            resultInfo.setData(mongoDB_s_c_webSocketMessageEntities);
        }

        packagedData.writeValue(resultInfo,httpServletResponse);
    }
    @RequestMapping("normalMessages")
    public void normalMessages(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException {
        UserEntity userEntity = (UserEntity)httpServletRequest.getSession().getAttribute("USER");
        List<MongoDB_S_C_WebSocketSendMessageEntity> normalMessages = messageCenterService.findNormalMessages(userEntity.getUname());
        PackagedData packagedData = new PackagedDataImpl();
        packagedData.writeValue(normalMessages,httpServletResponse);


    }
    @RequestMapping("deleteMessage")
    public void deleteMessage(@RequestParam String itemName, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        UserEntity userEntity = (UserEntity)httpServletRequest.getSession().getAttribute("USER");
        boolean b = messageCenterService.deleteMessage(itemName, userEntity.getUname());
        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        if (b){
            resultInfo.setFlag(true);
            resultInfo.setErrorMsg("删除成功！");
        }else {
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("删除错误！");
        }
        packagedData.writeValue(resultInfo,httpServletResponse);
    }

    // TODO: 2023/2/19 系统消息模块要重做
    @RequestMapping("sysMessage")
    public void sysMessage(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException {
        UserEntity userEntity = (UserEntity)httpServletRequest.getSession().getAttribute("USER");
        PackagedData packagedData = new PackagedDataImpl();
        List<User_RoleEntity> user_roleEntities = userLoginService.uidFindUser_Role(userEntity.getUid());
        List<MongoDB_S_C_WebSocketSendMessageEntity> sysMessages = messageCenterService.findSysMessages(user_roleEntities);
        packagedData.writeValue(sysMessages,httpServletResponse);
    }


/*String message,Integer date,Integer month,Integer hour,MessageType messageType*/
    @RequestMapping("sysMessageDelete")
    public void sysMessageDelete(@RequestParam String message,
                                 @RequestParam Integer date,
                                 @RequestParam Integer month,
                                 @RequestParam Integer hour,
                                 @RequestParam String messageType,
                                 HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse) throws IOException {
        MessageType messageType1 = CalculationIsType.calculationIsMessageType(messageType);
        boolean b = messageCenterService.deleteSysMessage(message, date, month, hour, messageType1);
        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        if (b) {
            resultInfo.setFlag(true);
            resultInfo.setErrorMsg("删除了一个"+messageType1.getValue()+"消息！");
        }else {
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("删除失败！");
        }
        packagedData.writeValue(resultInfo,httpServletResponse);

    }
    //用户认证
    @RequestMapping("findSysAuthAuditMessage")
    public void findSysAuthAuditMessage(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException {
        UserEntity userEntity = (UserEntity)httpServletRequest.getSession().getAttribute("USER");
        PackagedData packagedData = new PackagedDataImpl();
        ResultInfo resultInfo = new ResultInfo();
        Integer groupId = userEntity.getGroupId();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        resultInfo.setFlag(false);
        for (GrantedAuthority authority : authorities) {
            if (authority.toString().equalsIgnoreCase("u5")){
                Group_TBEntity group_tbEntity = messageCenterService.groupIdFindGroup(groupId);
                String group = group_tbEntity.getGroupContext();
                Collection<MongoDB_S_C_SysAuthAuditMessageEntity> userAuthAuditMessage = messageCenterService.findUserAuthAuditMessage(CalculationIsType.calculationIsGroupType(group));

                resultInfo.setFlag(true);
                resultInfo.setData(userAuthAuditMessage);

            }
        }
        packagedData.writeValue(resultInfo,httpServletResponse);
    }

    //日常点检审核
    @RequestMapping("findS_C_DailyAuditMessage")
    public void findS_C_DailyAuditMessage(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException {
        PackagedData packagedData = new PackagedDataImpl();
        ResultInfo resultInfo = new ResultInfo();
        List<MongoDB_S_C_SaveSCDailyContextEntity> mongoDB_s_c_webSocketMessageEntities = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        resultInfo.setFlag(false);
        for (GrantedAuthority authority : authorities) {
            if (authority.toString().equalsIgnoreCase("s4")) {
                Permission_TBEntity permission_tbEntity = new Permission_TBEntity(10, "s4", "点检业务审核");
                mongoDB_s_c_webSocketMessageEntities = messageCenterService.findS_C_DailyAuditMessage(permission_tbEntity);
            }
        }
        if (mongoDB_s_c_webSocketMessageEntities == null){
            resultInfo.setFlag(false);
        }else {
            resultInfo.setFlag(true);
            resultInfo.setData(mongoDB_s_c_webSocketMessageEntities);
        }

        packagedData.writeValue(resultInfo,httpServletResponse);
    }
    //审核通过
    @RequestMapping("auditPassBtnFun")
    public void auditPassBtnFun(@RequestParam String userName ,HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) throws IOException {
       boolean b = messageCenterService.auditPassBtnFun(userName);
       ResultInfo resultInfo = new ResultInfo();
       PackagedData packagedData = new PackagedDataImpl();
       resultInfo.setFlag(b);
       packagedData.writeValue(resultInfo,httpServletResponse);
    }
    //审核不通过
    @RequestMapping("auditNGBtnFun")
    public void auditNGBtnFun(@RequestParam String userName ,HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) throws IOException {
        boolean b = messageCenterService.auditNGBtnFun(userName);
        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        resultInfo.setFlag(false);
        if (b){
            resultInfo.setFlag(true);
        }
        packagedData.writeValue(resultInfo,httpServletResponse);
    }
    //获取业务消息的菜单
    @RequestMapping("getBMMessageMenu")
    public void getBMMessageMenu(HttpServletResponse httpServletResponse ,HttpServletRequest httpServletRequest) throws IOException {
        UserEntity user = (UserEntity) httpServletRequest.getSession().getAttribute("USER");
        List<Permission_TBEntity> permission_tbEntities = getUserPermission.GetPermission(user.getUname());
        Set<Integer> b_m_idS = new HashSet<>();
        if (!permission_tbEntities.isEmpty()){
            for (Permission_TBEntity permission_tbEntity : permission_tbEntities) {
                List<BusinessCenterMessageEntity_per> businessCenterMessageEntity_pers = messageCenterService.perIdFindBMMessageMid(permission_tbEntity);
                if (!businessCenterMessageEntity_pers.isEmpty()){
                    for (BusinessCenterMessageEntity_per businessCenterMessageEntity_per : businessCenterMessageEntity_pers) {
                        b_m_idS.add(businessCenterMessageEntity_per.getBmId());
                    }
                }
            }
        }

        List<BusinessCenterMessageEntity> businessCenterMessageEntities = messageCenterService.getBMMessageMenu(b_m_idS);
        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();
        if (businessCenterMessageEntities.isEmpty()){
            resultInfo.setFlag(false);
        }else {
            resultInfo.setFlag(true);
            resultInfo.setData(businessCenterMessageEntities);
        }
        packagedData.writeValue(resultInfo,httpServletResponse);
    }

    //获取业务消息的数量
    @RequestMapping("getBMMessageMenuCount")
    public void getBMMessageMenuCount(HttpServletResponse httpServletResponse ,HttpServletRequest httpServletRequest) throws IOException {
        ResultInfo resultInfo = new ResultInfo();
        PackagedData packagedData = new PackagedDataImpl();

        UserEntity user = (UserEntity)httpServletRequest.getSession().getAttribute("USER");
        List<User_RoleEntity> user_roleEntities = userFusionService.uidFindURole(user.getUid());
        List<Permission_TBEntity> permission_tbEntities = new ArrayList<>();
        for (User_RoleEntity user_roleEntity : user_roleEntities) {
            List<Urole_PermissionEntity> urole_permissionEntities = userFusionService.uRidFindURPermission(user_roleEntity.getUroleId());
            for (Urole_PermissionEntity urole_permissionEntity : urole_permissionEntities) {
                Permission_TBEntity permission_tbEntity = userFusionService.permissionIdFindpermission(urole_permissionEntity.getUPPermissionId());
                if (permission_tbEntity != null) {
                    permission_tbEntities.add(permission_tbEntity);
                }
            }
        }
        //点检项目的添加  开始
        Spot_CheckMessageCenterCountFusionEntity spot_checkMessageCenterCountFusionEntity = new Spot_CheckMessageCenterCountFusionEntity();
        int SCAddAuditCount = 0;
        List<MongoDB_S_C_WebSocketMessageEntity> SCAddAudit = null;
        for (Permission_TBEntity permission_tbEntity : permission_tbEntities) {
            if (permission_tbEntity.getPermission().equals("s3")){
                SCAddAudit = spot_check_fusionService.findMongoDB_S_C_WebSocketMessageEntity(permission_tbEntity);
                break;
            }
        }

        if (SCAddAudit != null ){
            SCAddAuditCount = SCAddAudit.size();

        }
        spot_checkMessageCenterCountFusionEntity.setSCAddAuditMessageCount(SCAddAuditCount);
        //点检项目的添加  结束
        //点检业务审核  开始
        int SCDailyAuditCount =0;
        List<MongoDB_S_C_SaveSCDailyContextEntity> SCDailyAudit = null;

        for (Permission_TBEntity permission_tbEntity : permission_tbEntities) {
            if (permission_tbEntity.getPermission().equals("s4")){
                SCDailyAudit = spot_check_fusionService.findMongoDB_S_C_SaveSCDailyContextEntity(permission_tbEntity);
                break;
            }
        }
        if (SCDailyAudit != null ){
            SCDailyAuditCount = SCDailyAudit.size();
        }
        spot_checkMessageCenterCountFusionEntity.setSCDailyAuditMessageCount(SCDailyAuditCount);
        //点检业务审核  结束
        //点检异常对应  开始
        int SCDailyExCount = 0;
        List<MongoDB_S_C_WebSocketMessageEntity> SCDailyEx = null;
        for (Permission_TBEntity permission_tbEntity : permission_tbEntities) {
            if (permission_tbEntity.getPermission().equals("s5")){

                SCDailyEx = spot_check_fusionService.findMongoDB_S_C_WebSocketMessageEntity(permission_tbEntity);
                break;
            }
        }
        if (SCDailyEx != null ){
            SCDailyExCount = SCDailyEx.size();

        }
        spot_checkMessageCenterCountFusionEntity.setSCDailyExMessageCount(SCDailyExCount);
        //点检异常对应  结束


        resultInfo.setData(spot_checkMessageCenterCountFusionEntity);
        packagedData.writeValue(resultInfo,httpServletResponse);

    }

    @RequestMapping("GetSCExMessage")
    public void GetSCExMessage(HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) throws IOException {
        PackagedData packagedData = new PackagedDataImpl();
        ResultInfo resultInfo = new ResultInfo();
        List<MongoDB_S_C_SaveSCDailyContextEntity> mongoDB_s_c_webSocketMessageEntities = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        resultInfo.setFlag(false);
        for (GrantedAuthority authority : authorities) {
            if (authority.toString().equalsIgnoreCase("s5")) {
                Permission_TBEntity permission_tbEntity = new Permission_TBEntity(13, "s5", "点检系统的异常对应");
                mongoDB_s_c_webSocketMessageEntities = messageCenterService.findS_C_ExMessage(permission_tbEntity);
            }
        }
        if (mongoDB_s_c_webSocketMessageEntities == null){
            resultInfo.setFlag(false);
        }else {
            resultInfo.setFlag(true);
            resultInfo.setData(mongoDB_s_c_webSocketMessageEntities);
        }



        packagedData.writeValue(resultInfo,httpServletResponse);
    }






}
